package com.scommunity.admin.controller;

import com.github.pagehelper.PageInfo;
import com.scommunity.admin.vo.EmpQO;
import com.scommunity.common.ResponseResult;
import com.scommunity.domain.Emp;
import com.scommunity.service.IEmpService;
import com.scommunity.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/admin/emp")
public class EmpController {
    @Autowired
    IEmpService empService;

    @Autowired
    JWTUtils jwtUtils;

    @PostMapping("/login")
    public Object login(@RequestBody Emp emp) {
        Emp e = empService.login(emp.getEmpAccount(), emp.getEmpPassword());
        if (e == null) {
            return ResponseResult.error(201, "user or password wrong");
        } else {
            if (e.getEmpStatus().equals("0")) {
                return ResponseResult.error(202, "账号异常");
            }
            String token = jwtUtils.getToken(e);
            return ResponseResult.success(token);
        }
    }

    @GetMapping({"/list/{pageNum}"})
    public Object list(EmpQO empQO, @PathVariable(required = false) Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageInfo<Emp> pageInfo = empService.findPageInfoByCondition(empQO, pageNum, 5);
        return ResponseResult.success(pageInfo);
    }

    @GetMapping("/getAll")
    public Object getAll() {
        List<Emp> emps = empService.getAll();
        return ResponseResult.success(emps);
    }

    @GetMapping("/getInfoByEmpId")
    public Object getInfoByEmpId(@SessionAttribute Emp emp, HttpServletRequest request) {
        String token = request.getHeader("token");
        Long id = jwtUtils.verifyToken(token).get("id");
        if (emp.getEmpId() == null) {
            emp.setEmpId(id);
        }
        Emp info = empService.getInfoByEmpId(emp.getEmpId());
        return ResponseResult.success(info);
    }

    @PostMapping("/add")
    public Object add(@RequestBody Emp emp) {
        empService.add(emp);
        return ResponseResult.success();
    }

    @PostMapping("/update")
    public Object update(@RequestBody Emp emp, HttpServletRequest request) {
        String token = request.getHeader("token");
        Long id = jwtUtils.verifyToken(token).get("id");
        if (emp.getEmpId() == null) {
            emp.setEmpId(id);
        }
        empService.update(emp);
        return ResponseResult.success();
    }

    @GetMapping("/del")
    public Object del(String id) {
        if (empService.getStatuseById(id) == 0) {
            empService.del(id);
            return ResponseResult.success();
        } else {
            return ResponseResult.error(201, "员工已启用，不能删除");
        }
    }

}
